﻿using IBLL;
using IDAL;
using Model;
using Model.DTO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;



namespace BLL
{
    public class ArrerBLL:ArrerIBLL
    {
        public ArrerBLL(IBaseDAL<Fanghao> Db,IBaseDAL<HouseNum>Db1, IBaseDAL<HouseType>Db2)
        {
            this.Db = Db;
            this.Db1 = Db1;
            this.Db2 = Db2;
        }

        public IBaseDAL<Fanghao> Db { get; }
        public IBaseDAL<HouseNum> Db1 { get; }
        public IBaseDAL<HouseType> Db2 { get; }

        public async Task<int> Add(Fanghao a)
        {
            try
            {
                await Db.AddAsync(a);
                var sd =  Db1.GetAll().FirstOrDefault(x => x.HouseNumId == a.HouseNumId);
                sd.HouseState = 2;
                await Db1.UpdateAsync(sd);
                return 1;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public Task<int> Delete(int id)
        {
            var s =  Db.GetAll().FirstOrDefault(x => x.ArrangId == id);
            return  Db.DeleteAsync(s);
        }

        public Fanghao GetArray(int id)
        {
            return Db.GetAll().FirstOrDefault(x => x.ArrangId == id);


        }

        public ArreayKKDTO Show(int pageIndex, int pageSize)
        {
            var q = Db.GetAll();
            var w = Db1.GetAll();
            var e = Db2.GetAll();
            var linq = from a in q
                       join b in w
                       on a.HouseNumId equals b.HouseNumId
                       join c in e
                       on b.HouseTypeId equals c.HouseTypeId
                       select new ArreayDTO
                       {
                           ArrangId = a.ArrangId,
                           HouseNumId = a.HouseNumId,
                           ArrangName = a.ArrangName,
                           ArrangPhone = a.ArrangPhone,
                           State = a.State,
                           HouseTypeName = c.HouseTypeName,
                           HouseNumName = b.HouseNumName
                       };
            ArreayKKDTO ko = new ArreayKKDTO();
            ko.Count = linq.Count();
            ko.Tang =linq.OrderBy(x=>x.ArrangId).Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
            return ko;
        }

        public Task<int> UpdateState(int a)
        {
            var s = Db.GetAll().FirstOrDefault(x => x.ArrangId == a);
            s.State = true;
            return Db.UpdateAsync(s);
        }
    }
}
